package com.jhz.speedy.component.net;

import com.jhz.speedy.common.util.LogUtils;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 日志打印拦截器
 * Created by JunHeZ on 2017/7/5.
 */
public class MyLogInterceptor implements Interceptor {
    private final String TAG = getClass().getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取请求
        Request request = chain.request();
        // 开始时间
        long startTime = System.currentTimeMillis();

        // 获取响应
        okhttp3.Response response = chain.proceed(chain.request());
        ResponseBody responseBody = response.body();
        okhttp3.MediaType mediaType = responseBody.contentType();
        String responseStr = responseBody.string();

        // 计算结束时间
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        // 打印请求内容
        LogUtils.d(TAG, "\n");
        LogUtils.d(TAG, "----------Start----------------");
        LogUtils.d(TAG, "| " + request.toString()); // 请求路径

        Headers headers = request.headers();
        String headersStr = headers.toString();
        LogUtils.d(TAG, "| headers:{" + headersStr + "}");  // 请求头

        String method = request.method();
        if ("POST".equals(method)) {    // POST请求打印参数
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                LogUtils.d(TAG, "| RequestParams:{" + sb.toString() + "}");
            }
        }

        // 打印响应内容
        LogUtils.d(TAG, "| Response:" + responseStr);
        LogUtils.d(TAG, "----------End:" + duration + "毫秒----------");

        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, responseStr))
                .build();
    }
}
